#!/bin/sh
#
# Start/Stop the WiFi-Radar daemon
#

# get the wifi interface from rc.inet1.conf if it is set
. /etc/rc.d/rc.inet1.conf
INTERFACE="${IFNAME[4]}"
PIDFILE=/var/run/wifi.pid

start() {
  # use the forced interface found in rc.inet1.conf or guess it
  [ ! "$INTERFACE" ] && INTERFACE="$(iwconfig 2>/dev/null | grep ESSID | head -n1 | cut -d " " -f 1)"
  sed -i "s/^[ \t]*interface[ \t]*=[ \t]*.*/interface = $INTERFACE/" /etc/wifi-radar.conf

  if [ -e "${PIDFILE}" ]; then
    echo "Found existing ${PIDFILE}! Stopping first before starting"
    stop
  fi
  echo "Starting WiFi-Radar: "
  /usr/sbin/wifi-radar --daemon 1> /dev/null 2> /dev/null &
   ps -e | grep wifi-radar | cut -d" " -f2 > ${PIDFILE}
}
 
stop() {
  echo "Stopping WiFi-Radar: "
  if [ -e "${PIDFILE}" ]; then
    kill $(cat ${PIDFILE}) 1> /dev/null 2> /dev/null
    rm -f ${PIDFILE}
  fi
killall wifi-radar 1> /dev/null 2> /dev/null
}
 
restart() {
  stop
  sleep 2
  start
}
 
status() {
  if [ -e ${PIDFILE} ]; then
    echo "The WiFi-Radar daemon is running."
  else
    echo "The WiFi-Radar daemon is not running"
  fi
}

# See how we were called.
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart}"
        ;;
esac
